package com.mock.ems.utils;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.mock.ems.redis.RedisHandler;
import com.mock.ems.redis.RedisSingleHandler;

public class TGlCateUtil {

    private static int init_status = 0;

    private static RedisHandler redisHandler = null;

    private static final String redisKey = "zmz.primary.key.max";
    /**
     * 增长段值
     */
    private static final Long increaseBound = 1000000l;
    /**
     * 当前DBID
     */
    private static Long dbid;
    /**
     * 当前递增的最大值
     */
    private static Long maxDbid;
    /**
     * 机器ID
     */
    private static Long machineId = 11L;
    /**
     * 机器名称 多台物理机器集群部署时，需要唯一区分
     */
    private static String machineName="dkm";

    /**
     * ID的基准长度
     */
    private static Long idBase = 10000000000000L;

    public static Long getId(){

        if(redisHandler == null){
            redisHandler = new RedisSingleHandler();
        }

        Long cateId = redisHandler.get(redisKey,Long.class);
        if( cateId == null ){
            init();
            cateId = getUniqueId();
            redisHandler.set(redisKey,cateId);
        }

        return redisHandler.incr(redisKey,1L);
    }

    public static void init(){
        Record glIdRecord =
                Db.findFirst("select * from t_gl_id where id_ = ? and mac_name_= ?",machineId,machineName);
        if(glIdRecord != null){
            dbid = glIdRecord.getLong("start_");
            maxDbid = glIdRecord.getLong("max_");
        }else{
            dbid = 1l;
            maxDbid = -1l;
        }
    }

    public static Long genLid() {
        return getUniqueId();
    }

    /**
     * 获取唯一的ID标识
     *
     */
    private static synchronized Long getUniqueId() {
        if (dbid > maxDbid) {
            genNextDbIds();
        }
        Long nextId = dbid++;
        return nextId + machineId * idBase;
    }
    private static Long genNextDbIds() {
//        String sql = "UPDATE t_gl_id SET start_=?,max_=? WHERE id_=?";
        dbid = maxDbid;
        maxDbid += increaseBound;
        Record record = new Record();
        record.set("start_",dbid).set("max_",maxDbid).set("id_",machineId);
        Db.update("t_gl_id","id_",record);
        return null;
    }
}
